package servlet;

import bean.Arrence;
import bean.Student;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        查询数据库
        String sql = "select * from student" ;
        ResultSet rs = DBUtil.query(sql);
//        设置一个集合
        ArrayList<Student> list = new ArrayList<>();
//        将结果封装到集合
        try {
            while(rs.next()) {
                int sid = rs.getInt("sid");
                String sname = rs.getString("sname");
                Student Student = new Student( sid, sname);
                list.add(Student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        将集合添加到 request 域中
        req.setAttribute("list",list);
        //        挑转到jsp表单
        req.getRequestDispatcher("/WEB-INF/add.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String sid = req.getParameter("sid");
        String time = req.getParameter("time");
        String type = req.getParameter("type");
//      编写SQL语句
        String sql = "insert into attence values (?,?,?,?)";
        int i = DBUtil.update(sql,null,time,type,sid);
        if (i>0){
            req.setAttribute("msg","添加成功");
            req.getRequestDispatcher("/WEB-INF/msg.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","添加失败");
            req.getRequestDispatcher("/WEB-INF/msg.jsp").forward(req,resp);
        }

    }
}
